package com.zhongke.common.imageloader

import android.graphics.drawable.Drawable
import android.widget.ImageView
import androidx.annotation.Dimension
import coil.ImageLoader
import coil.imageLoader
import coil.load
import coil.request.Disposable
import coil.request.ImageRequest
import coil.request.ImageResult
import com.bumptech.glide.load.ImageHeaderParser

/**
 *@Date: 2022/5/9
 *@Time: 16:56
 *@Author:cxc
 *@Description:图片加载拓展方法
 */

inline fun ImageView.loadNormal(
    data: Any?,
    options: ImageRequest.Builder.() -> Unit = {}
): Disposable {
    return this.defaultLoad(data, options = options)
}

/**
 * 圆角图片
 * @receiver ImageView
 * @param data Any?  图片源
 * @param radius Int  圆角大小
 * @param cornerType Int 圆角方向
 * @param options [@kotlin.ExtensionFunctionType] Function1<Builder, Unit>
 * @return Disposable
 */
inline fun ImageView.loadCorner(
    data: Any?,
    @Dimension(unit = Dimension.DP) radius: Int = 0,
    @CornerType cornerType: Int = CornerType.ALL,
    options: ImageRequest.Builder.() -> Unit = {}
): Disposable {
    return this.defaultLoad(
        data,
        radius = radius,
        imageType = ImageType.CORNER,
        type = cornerType,
        options = options
    )
}

/**
 * 圆形图片
 * @receiver ImageView
 * @param data Any? 图片源
 * @param options [@kotlin.ExtensionFunctionType] Function1<Builder, Unit>
 * @return Disposable
 */
inline fun ImageView.loadRound(
    data: Any?,
    options: ImageRequest.Builder.() -> Unit = {}
): Disposable {
    return this.defaultLoad(data, imageType = ImageType.ROUND, options = options)
}

/**
 * 加载图片的默认实现
 */
inline fun ImageView.defaultLoad(
    data: Any?,
    @Dimension(unit = Dimension.DP) radius: Int = 0,
    @ImageType imageType: Int = ImageType.NORMAL,
    @CornerType type: Int = CornerType.ALL,
    imageLoader: ImageLoader = context.imageLoader,
    options: ImageRequest.Builder.() -> Unit = {}
): Disposable {
    return ZKCoilDefaultImageLoader.loadImage(
        this,
        data,
        radius,
        imageType,
        type,
        imageLoader,
        options
    )
}

suspend inline fun ImageView.loadAsDrawable(
    data: Any?,
    imageLoader: ImageLoader = context.imageLoader,
    builder: ImageRequest.Builder.() -> Unit = {}
): Drawable? {
    val request = ImageRequest.Builder(context)
        .apply(builder)
        .data(data)
        .target(this)
        .build()
    return imageLoader.execute(request).drawable
}